package com.dailyblue.java.spring.mvc.config;

import com.dailyblue.java.spring.mvc.interceptor.FirstInterceptor;
import com.dailyblue.java.spring.mvc.interceptor.FourthInterceptor;
import com.dailyblue.java.spring.mvc.interceptor.SecondInterceptor;
import com.dailyblue.java.spring.mvc.interceptor.ThirdInterceptor;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import javax.annotation.Resource;

@Configuration
@EnableWebMvc  //开启SpringMVC
@ComponentScan({"com.dailyblue.java.spring.mvc.controller", "com.dailyblue.java.spring.mvc.interceptor"})
public class SpringMVCConfig implements WebMvcConfigurer {
    @Resource
    private FirstInterceptor firstInterceptor;
    @Resource
    private SecondInterceptor secondInterceptor;
    @Resource
    private ThirdInterceptor thirdInterceptor;
    @Resource
    private FourthInterceptor fourthInterceptor;

    // 视图解析器
    public void configureViewResolvers(ViewResolverRegistry registry) {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        // 就会跟controller方法的返回结果一起组装成页面路径
        viewResolver.setSuffix(".jsp");
        viewResolver.setPrefix("/");
        viewResolver.setExposeContextBeansAsAttributes(true);
        registry.viewResolver(viewResolver);
    }

    // 注册拦截器
    public void addInterceptors(InterceptorRegistry registry) {
        /*
            .addInterceptor(firstInterceptor)注册拦截器
            .addPathPatterns("/**")对那些请求拦截
            .excludePathPatterns("/second/a")对那些请求不拦截
         */
        registry.addInterceptor(firstInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/second/a").order(9);
        registry.addInterceptor(secondInterceptor)
                .addPathPatterns("/**").order(2);
        registry.addInterceptor(thirdInterceptor)
                .addPathPatterns("/**").order(5);
        registry.addInterceptor(fourthInterceptor)
                .addPathPatterns("/**").order(7);
    }

    // 允许静态资源访问
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}
